<template>
  <a-spin :spinning="confirmLoading">
    <a-table
      v-if="!formDisabled"
      style="margin-top: 10px"
      ref="table"
      size="middle"
      :scroll="{x:true}"
      bordered
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="false"
      class="j-table-force-nowrap1"
    >
    </a-table>
    <j-form-container :disabled="formDisabled" v-if="!formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="目标仓库" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="targetWarehouseCode">
              <j-dict-select-tag
                @change="handleTargetWarehouseChange"
                placeholder="请选择目标仓库"
                v-model="model.targetWarehouseCode"
                :dictCode="warehouseDictCode" />
            </a-form-model-item>
          </a-col>
          <!--
          <a-col :span="24">
            <a-form-model-item label="目标储位" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="targetStorageLocation">
              <select-storage-location
                placeholder="请选择储位"
                :warehouse-code="model.targetWarehouseCode"
                v-model="model.targetStorageLocation" />
            </a-form-model-item>
          </a-col>
          -->
          <a-col :span="24">
            <a-form-model-item label="调拨数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="transferQuantity">
              <a-input-number v-model="model.transferQuantity" placeholder="请输入数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <a-table
      v-if="formDisabled"
      style="margin-top: 10px"
      ref="table"
      size="middle"
      :scroll="{x:true}"
      bordered
      rowKey="id"
      :columns="detailColumns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="tableLoading"
      class="j-table-force-nowrap1"
       @change="handleTableChange"
    >
        <span slot="action" slot-scope="text, record">
          <span v-if="record.status === '1'">已完成</span>
          <span v-else-if="record.status === '2'">已撤销</span>
          <a-popconfirm
            title="确定撤销吗?"
            v-else-if="record.status === '0'"
            @confirm="() => handleCancel(record)">
            <a>撤销</a>
          </a-popconfirm>
        </span>
    </a-table>
  </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import SelectStorageLocation from '@comp/warehouse/SelectStorageLocation.vue'

export default {
  name: 'TransferRecordForm',
  components: { SelectStorageLocation },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      warehouseCode: null,
      warehouseType: null,
      excludeLocationCode: null,
      model: {
        targetWarehouseCode: null,
        targetStorageLocation: null
      },
      record: {},
      tableLoading: false,
      columns: [
        {
          title: '单据类型',
          align: 'center',
          dataIndex: 'documentType_dictText',
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'specificationModel'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'quantity'
        },
        {
          title: '生产日期',
          align: 'center',
          dataIndex: 'productionDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '保质期（天）',
          align: 'center',
          dataIndex: 'shelfLife'
        },
        {
          title: '限用日期',
          align: 'center',
          dataIndex: 'expirationDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '批次号',
          align: 'center',
          dataIndex: 'batchNumber'
        },
        {
          title: '物料批号',
          align: 'center',
          dataIndex: 'materialBatchNumber'
        },
        {
          title: '储位',
          align: 'center',
          dataIndex: 'storageLocation_dictText'
        },
        {
          title: '入库日期',
          align: 'center',
          dataIndex: 'entryDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '库龄（天）',
          align: 'center',
          dataIndex: 'inventoryAge'
        },
        {
          title: '质检状态',
          align: 'center',
          dataIndex: 'qualityInspectionStatus_dictText'
        }
      ],
      dataSource: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        targetWarehouseCode: [
          { required: true, message: '请选择目标仓库!' }
        ],
        /*
        targetStorageLocation: [
          { required: true, message: '请选择目标储位!' }
        ],
         */
        transferQuantity: [
          { required: true, message: '请输入数量!' }
        ]
      },
      url: {
        add: '/wms/transfer-record/transfer',
        edit: '/wms/transfer-record/edit',
        queryById: '/wms/transfer-record/queryById',
        list: '/wms/transfer-record/list',
        inventoryQueryById: '/wms/inventory/queryById'
      },
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    detailColumns() {
      return [
        {
          title: '单据类型',
          align: 'center',
          dataIndex: 'documentType_dictText',
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'specificationModel'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        // {
        //   title: '数量',
        //   align: 'center',
        //   dataIndex: 'quantity'
        // },
        {
          title: '调拨数量',
          align: 'center',
          dataIndex: 'transferQuantity'
        },
        {
          title: '生产日期',
          align: 'center',
          dataIndex: 'productionDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '保质期（天）',
          align: 'center',
          dataIndex: 'shelfLife'
        },
        {
          title: '限用日期',
          align: 'center',
          dataIndex: 'expirationDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '批次号',
          align: 'center',
          dataIndex: 'batchNumber'
        },
        {
          title: '物料批号',
          align: 'center',
          dataIndex: 'materialBatchNumber'
        },
        {
          title: '储位',
          align: 'center',
          dataIndex: 'storageLocation_dictText'
        },
        {
          title: '入库日期',
          align: 'center',
          dataIndex: 'entryDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '库龄（天）',
          align: 'center',
          dataIndex: 'inventoryAge'
        },
        {
          title: '质检状态',
          align: 'center',
          dataIndex: 'qualityInspectionStatus_dictText'
        },
        {
          title: '目标仓库',
          align: 'center',
          dataIndex: 'targetWarehouseCode_dictText'
        },
        // {
        //   title: '目标储位',
        //   align: 'center',
        //   dataIndex: 'targetStorageLocation_dictText'
        // },
        {
          title: '操作人',
          align: 'center',
          dataIndex: 'createBy_dictText'
        },
        {
          title: '操作时间',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 60,
          scopedSlots: { customRender: 'action' }
        }
      ]
    },
    warehouseDictCode() {
      let dictCode = 'wms_warehouse,warehouse_name,warehouse_code'
      return dictCode
      /*
      if (this.warehouseType) {
        dictCode = dictCode + `,(warehouse_type='${this.warehouseType}' and warehouse_code<>\'${this.warehouseCode}\')`
        if (this.warehouseType === 1) {
          dictCode = dictCode + `or warehouse_code in ('W06','W07','W08')`
        }
      }
      return dictCode
       */
    }
  },
  created() {
    if (this.formDisabled) {
      this.fetchData()
    }
  },
  methods: {
    add(record) {
      this.record = Object.assign({}, record)
      this.model.sourceInventoryId = this.record.id
      this.dataSource.push(this.record)
      this.fetchInventoryData()
      this.visible = true
    },
    fetchInventoryData() {
      getAction(this.url.inventoryQueryById, { id: this.record.id })
        .then(({ result }) => {
          if (result) {
            this.warehouseType = result.warehouseType
            this.warehouseCode = result.warehouseCode
          }
        })
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          postAction(this.url.add, this.model).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    handleTargetWarehouseChange() {
      this.model.targetStorageLocation = null
    },
    // 处理分页变化
    handleTableChange(pagination) {
      this.ipagination.current = pagination.current;
      this.ipagination.pageSize = pagination.pageSize;
      this.fetchData();
    },
    fetchData() {
      this.tableLoading = true
      const params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize
      }
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          if (res.result.records.length) {
            res.result.records.forEach(item => {
              item.storageLocation_dictText = item.sourceStorageLocation_dictText
            })
          }
          this.dataSource = res.result.records
          this.dataSourceBack = this.dataSource
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    handleCancel(record) {
      postAction('/wms/transfer-record/revoke', { id: record.id })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        })
    }
  }
}
</script>